const http = require('http'); // http是内置的，url也是
const url = require('url'); // 用于解析处理url
const router = require('./router'); // 业务分离后的route

const app = http.createServer((req, res) => {
  let path = null; // 存放路由
  let searchParams = {}; // 存放get请求参数

  if (req.method === 'GET') {
    // 处理get请求
    // parse true是将path转化为对象object
    let { pathname, query } = url.parse(req.url, true);
    path = pathname;
    searchParams = query;
    handleGetMethod();
  }

  function handleGetMethod() {
    // 根据路由处理请求
    if (path === '/TrueApi') {
      const { url = '' } = searchParams;
      router.getTrueApi(req, res, url);
    } else if (path === '/AddApi') {
      // 新增mock api，并保存api的请求响应格式
      router.addApi(req, res, searchParams);
    } else if (path === '/removeApi') {
      // 获取所有mock api名称
      router.removeApi(req, res, searchParams);
    } else if (path === '/QueryApiList') {
      // 获取所有mock api名称
      router.queryApiList(req, res);
    } else if (path === '/GetApiDetail') {
      // 获取对应mock api的请求响应格式
      router.queryApiDetail(req, res, searchParams);
    } else {
      // 如果没有对应的路由，作为静态资源处理
      router.getPage(req, res, path);
    }
  }
});

app.listen(3001, () => {
  console.log('port 3001 is running...');
});